package com.dongdong.MQ;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/*MQ消费*/
@Component
@RocketMQMessageListener(consumerGroup = "dk2209-wxy",topic = "generateCode")
public class generateCode implements RocketMQListener<String> {

    @Value("${apicode.accessKeyId}")
    private String accessKeyId;

    @Value("${apicode.accessKeySecret}")
    private String accessKeySecret;

    @Value("${apicode.region}")
    private String region;

    @Value("${apicode.setEndpointOverride}")
    private String setEndpointOverride;

    @Value("${apicode.signName}")
    private String signName;

    @Value("${apicode.templateCode}")
    private String templateCode;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void onMessage(String phone) {//拿到手机号
        System.out.println(phone);

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)//LTAI5tRVYYLS4pnrXYxMosn8     阿里Key
                .accessKeySecret(accessKeySecret)//uUi4zbsHPHe1s2LM1Zu4X9v0YRBCgn   密钥
                //.securityToken("<your-token>") // use STS token
                .build());

        AsyncClient client = AsyncClient.builder()
                .region(region) // Region ID    地域  杭州  北京
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(setEndpointOverride)
                )
                .build();

        //生成验证码
        String s = RandomUtil.randomNumbers(6);
        JSONObject json = new JSONObject();
        json.put("code",s);
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)          //签名
                .templateCode(templateCode)   //模板名称
                .phoneNumbers(phone)         //要发消息至 - 手机号
                .templateParam(json.toJSONString())   //将生成的验证码放入缓存    由于格式  所以需要转换
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(new Gson().toJson(resp));


        /*将验证码放入缓存  并且设置超时间   一般是一分钟后失效*/
        stringRedisTemplate.opsForValue().set(phone,s);/*手机号码 的 验证码*/
        stringRedisTemplate.boundValueOps(phone).expire(1, TimeUnit.MINUTES);/*30分钟失效    MINUTES:分钟   expire:失效*/

        // Finally, close the client
        client.close();
        System.out.println("ok");
    }
}
